use askama_axum::{IntoResponse, Template};
use axum::extract::{Path, State};
use axum::response::Redirect;
use axum::Form;
use tower_cookies::Cookies;
use tower_sessions::Session;

use crate::controllers::backend::ErrorTemplate;
use crate::core::xerror::{GLOBALERROR, XErrors};
use crate::core::AppState;
use crate::services::backend::category_service::CategoryService;
use crate::types::backend::category_type::{CategoryRow, CategoryForm};
use crate::types::common::Breadcrumb;

use super::AdminSession;


#[derive(Template)]
#[template(path = "backend/category/list.html")]
struct CategoryListTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    list: Vec<CategoryRow>
}

#[derive(Template)]
#[template(path = "backend/category/form.html")]
struct CategoryFormTemplate {
    auth: AdminSession,
    breadcrumb: Breadcrumb,
    data: CategoryForm,
    url: String
}

/// 获取文章分类分页列表
pub async fn categorys_handler(State(state): State<AppState>, session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;

    let breadcrumb = Breadcrumb {
        title: "文章分类管理".to_string(),
        sub_title: "文章分类列表".to_string(),
    };

    let res = CategoryService::get_categorys(&state.db).await;
    
    match res {
        Ok(data) => {
            let template = CategoryListTemplate { 
                auth,
                breadcrumb,
                list: data
            };
            return axum::response::Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate{
                msg: e.to_string()
            };
            return axum::response::Html(template.render().unwrap())
        }
    }
}

/// 添加文章分类表单
pub async fn add_category_handler(session: Session) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    
    let breadcrumb = Breadcrumb {
        title: "文章分类管理".to_string(),
        sub_title: "添加文章分类".to_string(),
    };

    let template = CategoryFormTemplate { 
        auth,
        breadcrumb,
        data: CategoryForm { 
            name: "".to_string(), 
            image: "".to_string(), 
            order_by: 0
        },
        url: "/backend/category/create".to_string()
    };
    return axum::response::Html(template.render().unwrap());
}

// 添加文章分类操作
pub async fn create_category_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Form(form): Form<CategoryForm>) -> Redirect {
    let error = XErrors::new();
    if form.name == "" {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to("/backend/category/create")
    }
    let res = CategoryService::insert_category(&state.db, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::ADDSUCCESS, "".to_string());
            return Redirect::to("/backend/category/list")
        }, 
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::ADDFAILED, db_error);
            return Redirect::to("/backend/category/list")
        }
    }
}

/// 修改文章分类表单
pub async fn edit_category_handler(State(state): State<AppState>, session: Session, Path(id): Path<i64>) -> impl IntoResponse {
    let auth = AdminSession::init(session).await;
    let res = CategoryService::get_category_by_id(&state.db, id).await;
    let breadcrumb = Breadcrumb {
        title: "文章分类管理".to_string(),
        sub_title: "修改文章分类".to_string(),
    };
    match res {
        Ok(data) => {
            let template = CategoryFormTemplate { 
                auth,
                breadcrumb,
                data,
                url: "/backend/category/edit/".to_string() + &id.to_string()
             };
            return axum::response::Html(template.render().unwrap())
        },
        Err(e) => {
            let template = ErrorTemplate{ 
                msg: e.to_string(), 
            };
            return axum::response::Html(template.render().unwrap())
        }
    }
}

// 修改文章分类操作
pub async fn update_category_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>,
    Form(form): Form<CategoryForm>) -> Redirect {
    let error = XErrors::new();
    if form.name == "" {
        error.set_cookie_error(cookies, GLOBALERROR::PARAMINVALIDFAILED, "".to_string());
        return Redirect::to(format!("/backend/category/edit/{}", id).as_str());
    }

    // 有数据则更新
    let res = CategoryService::update_category(&state.db, id, &form).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::UPDATESUCCESS, "".to_string());
            return Redirect::to("/backend/category/list")
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::UPDATEFAILED, db_error);
            return Redirect::to("/backend/category/list")
        }
    }
}

/// 删除文章分类操作
pub async fn delete_category_handler(
    State(state): State<AppState>, 
    cookies: Cookies,
    Path(id): Path<i64>) -> Redirect {
    let error = XErrors::new();
    let exist = CategoryService::exist_category_by_id(&state.db, id).await;
    let total = match exist {
        Ok(total) => total,
        Err(_) => 0,
    };
    if total == 0 {
        error.set_cookie_error(cookies, GLOBALERROR::RECORDNOTFOUND, "".to_string());
        return Redirect::to("/backend/category/list");
    }

    let res = CategoryService::delete_category(&state.db, id).await;
    match res {
        Ok(_) => {
            error.set_cookie_error(cookies, GLOBALERROR::DELETESUCCESS, "".to_string());
            return Redirect::to("/backend/category/list")
        },
        Err(e) => {
            let db_error = e.to_string();
            error.set_cookie_error(cookies, GLOBALERROR::DELETEFAILED, db_error);
            return Redirect::to("/backend/category/list")
        }
    }
}
